package com.cjp.run.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cjp.run.Application;
import com.cjp.utils.FileUtils;
import com.cjp.utils.SymmetricEncoder;

@RestController
public class AdminController {
	
	/**
	 * 新增定时模板
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/add")
	public String save(@RequestBody String params){
		JSONObject result=new JSONObject();
		String id=UUID.randomUUID().toString()+System.currentTimeMillis();
		JSONObject data=new JSONObject();
		JSONObject json=JSONObject.parseObject(params);
		try {
			String tempDate=null;
			File file=null;
			if(json.containsKey("createTime")&&json.getString("createTime")!=null){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat f=new SimpleDateFormat("yyyyMMdd");
				tempDate=f.format(format.parse(json.getString("createTime")));
				id=json.getString("id");
				file=FileUtils.readTemplateFile(tempDate, json.getString("id"));
				JSONObject contentJson=FileUtils.readTemplate(tempDate, id);
				if("1".equals(contentJson.getString("isSend"))){
					result.put("code", 500);
					System.out.println("已发送的消息不能更改");
					return result.toString();
				}
				data.put("createTime", json.getString("createTime"));
			}else{
				data.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			}
			data.put("sendTime", "");//实际发送时间
			data.put("setSendTime", json.getString("sendDate"));//预计发送时间
			data.put("templateId", json.getString("templateId"));
			data.put("templateName", json.getString("templateName"));
			data.put("isSend", "0");
			data.put("id", id);
			if(json.containsKey("note")){
				data.put("note", json.getString("note"));
				json.remove("note");
			}
			
			if(json.containsKey("topcolor")){
				data.put("topcolor", json.getString("topcolor"));
				json.remove("topcolor");
			}
			
			if(json.containsKey("templateContent")){
				data.put("templateContent", json.getString("templateContent"));
				json.remove("templateContent");
			}
			
			data.put("clickurl", json.getString("clickurl"));
			json.remove("sendDate");
			json.remove("templateId");
			json.remove("clickurl");
			data.put("data", json.toString());
			if(file!=null){
				FileUtils.write(file, data.toString());
			}else{
				FileUtils.write(id, data.toString());
			}
			//记录预览的openid
			FileUtils.createDir("openlist");
			FileUtils.write("openlist","openidlist",json.getJSONObject("openid").toString(),false);
			
			JSONObject templateJson=new JSONObject();
			templateJson.put("templateId", data.getString("templateId"));
			templateJson.put("templateName", data.getString("templateName"));
			if(data.containsKey("templateContent")){
				templateJson.put("templateContent", data.getString("templateContent"));
			}
			//记录使用过的模板ID
			FileUtils.createDir("templateUse");
			FileUtils.write("templateUse",data.getString("templateId"), templateJson.toString(),false);
			
			result.put("code", 200);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 500);
		}
		return result.toString();
	}
	
	@RequestMapping("/getTemplateUse")
	@ResponseBody
	public String getTemplateUse(){
		JSONArray json=FileUtils.read("templateUse");
		return json==null?"":json.toString();
	}
	
	@RequestMapping("/getOpenlist")
	@ResponseBody
	public String getOpenlist(){
		JSONArray json=FileUtils.read("openlist");
		return json!=null?json.getJSONObject(0).toString():null;
	}
	
	/**
	 * 删除定时模板
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public String delete(@RequestParam String createDate,@RequestParam String id){
		JSONObject result=new JSONObject();
		JSONObject json=FileUtils.readTemplate(createDate, id);
		if("1".equals(json.getString("isSend"))){
			result.put("code", 500);
			System.out.println("已发送的消息不能删除");
			return result.toString();
		}
		File file=FileUtils.readTemplateFile(createDate, id);
		try {
			if(file.exists()){
				file.delete();
			}
			result.put("code", 200);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 500);
		}
		return result.toString();
	}
	
	/**
	 * 预览
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/search")
	public String search(@RequestBody String params){
		JSONObject result=new JSONObject();
		try {
			JSONObject json=JSONObject.parseObject(params);
			JSONObject openlist=json.getJSONObject("openid");
			if(openlist==null){
				result.put("code", 200);
				return result.toString();
			}
			Iterator<String> iter=openlist.keySet().iterator();
			while(iter.hasNext()){
				String value=openlist.getString(iter.next());
				try {
					System.out.println("发送："+value);
					String r=Application.sendWechatmsgToUser(value, json.getString("templateId"), json.getString("clickurl"), json.getString("clickurl"), json);
					System.out.println("发送结果："+r);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			result.put("code", 200);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 500);
		}
		return result.toString();
	}
	
	
	/**
	 * 查询定时模板
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/get")
	public String get(@RequestParam String date){
		JSONArray json=FileUtils.read(date);
		return json==null?"":json.toString();
	}
	
	

	/**
	 * 查询公众号列表
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/getAppList")
	public String getAppList(){
		JSONArray json=FileUtils.readApp("app");
		if(json!=null){
			for(int i=0;i<json.size();i++){
				JSONObject o=json.getJSONObject(i);
				o.put("APPSECRET", SymmetricEncoder.AESDncode("APPSECRETKEY", o.getString("APPSECRET")).substring(0,4)+"********");
			}
		}
		return json==null?"":json.toString();
	}
	/**
	 * 查询公众号列表
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/getApp")
	public String getApp(HttpServletRequest request){
		JSONObject json=FileUtils.readTemplateApp("app",FileUtils.currentAppidThread.get());
		return json==null?"":json.toString();
	}
	
	/**
	 * 查询公众号列表
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/insertApp")
	public String insertApp(@RequestBody String params){
		JSONObject result=new JSONObject();
		try {
			JSONObject jsonObject=JSONObject.parseObject(params);
			try {
				FileUtils.currentAppidThread.set(jsonObject.getString("APPID").trim());
				FileUtils.currentAppAppsecretThread.set(jsonObject.getString("APPSECRET").trim());
				Application.isValid();
			} catch (Exception e) {
				e.printStackTrace();
				result.put("code", 500);
				result.put("msg", "无效的APPID或APPSECRET，请向公众号管理员索取");
				return result.toString();
			}
			
			if(!StringUtils.isEmpty(jsonObject.getString("APPSECRET"))){
				jsonObject.put("APPSECRET", SymmetricEncoder.AESEncode("APPSECRETKEY", jsonObject.getString("APPSECRET").trim()));
			}
			jsonObject.put("APPID", jsonObject.getString("APPID").trim());
			FileUtils.writeApp("app",jsonObject.getString("APPID"), jsonObject.toString(),false);
			result.put("code", 200);
			result.put("msg", "新增成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 500);
			result.put("msg", "新增失败");
		}
		return result.toString();
	}
	
	
	
	/**
	 * 设置当前操作的APPID
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/setCurrentAppId")
	public String setCurrentAppId(@RequestParam String appid,HttpServletRequest request){
		JSONObject result=new JSONObject();
		request.getSession().setAttribute("currentAppId", appid);
		JSONObject json=FileUtils.readTemplateApp("app",appid);
		request.getSession().setAttribute("currentAppsecret", SymmetricEncoder.AESDncode("APPSECRETKEY", json.getString("APPSECRET")));
		result.put("code", 200);
		return result.toString();
	}
	
	
	/**
	 * 查询定时模板
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/getByTemplate")
	public String getByTemplate(@RequestParam String createDate,@RequestParam String id){
		JSONObject json=FileUtils.readTemplate(createDate,id);
		return json==null?"":json.toString();
	}
	@ResponseBody
	@RequestMapping("/parseTemplate")
	public String parseTemplate(@RequestBody String params){
		JSONObject paramsJson=JSONObject.parseObject(params);
		JSONObject json=new JSONObject();
		System.out.println(paramsJson.getString("key"));
		//String s="{{first.DATA}} 投诉内容：{{key_word1.DATA}} 联系方式：{{key-word2.DATA}} {{remark.DATA}}";
		Pattern pattern = Pattern.compile("[{]{2}[a-z|A-Z|0-9|.|_|-]*[}]{2}");
        Matcher matcher = pattern.matcher(paramsJson.getString("key"));
        int i=1;
        while(matcher.find()){
        	Pattern p = Pattern.compile("[a-z|A-Z|0-9|.|_|-]*");
        	Matcher m = p.matcher(matcher.group());
        	while(m.find()){
        		String key=m.group().replace(".DATA", "");
        		if("".equals(key.trim())){
        			continue;
        		}
        		if("first".equals(key.trim())){
        			continue;
        		}
        		if("remark".equals(key.trim())){
        			continue;
        		}
        		System.out.println(key);
        		json.put("keyword"+i, key);
        		i++;
        	}
        }
        return json.toString();
	}
}
